import glob
import os
from PIL import Image
from util import get_project_root

Root_path = get_project_root()

#切图
def cut_image(image):
    width, height = image.size
    N = 8
    item_width = int(width / N)
    box_list = []
    # (left, upper, right, lower)
    for i in range(0, N): # 两重循环，生成16张图片基于原图的位置
        for j in range(0, N):
            #print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width))
            box = (j*item_width, i*item_width, (j+1)*item_width, (i+1)*item_width)
            box_list.append(box)
    image_list = [image.crop(box) for box in box_list]
    return image_list


#保存
def save_images(image_list, image_name):
    for index, image in enumerate(image_list):
        image.save(Root_path + '/data/pathol32/32/' + image_name + '_' + str(index) + '.jpg')

if __name__ == '__main__':
    data_path = Root_path + "/data/pathol256"
    imgs_path = glob.glob(os.path.join(data_path, '*/*.jpg'), recursive=True)
    for img in imgs_path:
        # print(img.split("\\")[-1].split(".")[0])
        image_name = img.split("\\")[-1].split(".")[0]
        print(image_name)
        image = Image.open(img)
        image_list = cut_image(image)
        save_images(image_list, image_name)